package org.jeecg.modules.app.userSetting.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xkcoding.http.HttpUtil;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.modules.app.userSetting.entity.AppUserSetting;
import org.jeecg.modules.app.userSetting.mapper.AppUserSettingMapper;
import org.jeecg.modules.app.userSetting.service.AppUserSettingService;
import org.jeecg.modules.system.entity.SysFiles;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysFilesService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description: 移动端用户扩展表
 * @Author: jeecg-boot
 * @Date: 2025-06-13
 * @Version: V1.0
 */
@Service
public class AppUserSettingServiceImpl extends ServiceImpl<AppUserSettingMapper, AppUserSetting> implements AppUserSettingService {

    @Value("${config.applet.sso}")
    private String sso;
    @Value("${config.applet.appId}")
    private String appId;
    @Value("${config.applet.appSecret}")
    private String appSecret;

    @Resource
    private ISysUserService userService;
    @Resource
    private ISysFilesService filesService;

    @Override
    public Result<String> beforeLogin(JSONObject params) {

        if (params == null || !params.containsKey("code")) {
            return Result.error("参数错误");
        }
        String code = params.getString("code");

        JSONObject wxUser = getWeChatSession(code);

        // 检查微信接口是否返回错误
        if (wxUser != null && wxUser.containsKey("errcode")) {
            String errmsg = wxUser.getString("errmsg");
            log.error("微信接口错误: " + errmsg);
            return Result.error("微信登录失败");
        }

        if (wxUser != null && wxUser.containsKey("openid")) {
            String openid = wxUser.getString("openid");
            // 查找是否有这个openid
            LambdaQueryWrapper<AppUserSetting> appQueryWrapper = new LambdaQueryWrapper<>();
            appQueryWrapper.eq(AppUserSetting::getOpenid, openid);

            AppUserSetting appUserSetting = this.getOne(appQueryWrapper);

            if (appUserSetting == null) {
                AppUserSetting appUser = new AppUserSetting();

                if (params.containsKey("userId") && params.getString("userId") != null) {
                    appUser.setUserId(params.getString("userId"));
                    appUser.setIsPrimary("1");
                } else {
                    appUser.setUserId("0");
                    appUser.setIsPrimary("0");
                }
                appUser.setOpenid(openid);

                String unionid = wxUser.getString("unionid");

                if (wxUser.containsKey("unionid") && wxUser.getString("unionid") != null) {
                    appUser.setUnionid(unionid);
                }
                appUser.setCreateBy("admin");
                appUser.setCreateTime(new Date());

                this.save(appUser);
                
                // 返回新创建的用户ID
                return Result.ok(appUser.getUserId());
            }

            // 返回已存在的用户ID
            return Result.ok(appUserSetting.getUserId());
        } else {
            return Result.error("获取微信session失败");
        }
    }

    /**
     * 根据用户openid获取扩展设置
     *
     * @author zwf
     * @date created in 2025-06-17 14:13
     * @param: openid
     * @return: org.jeecg.modules.app.userSetting.entity.AppUserSetting
     */
    @Override
    public AppUserSetting getByOpenId(String openid) {

        LambdaQueryWrapper<AppUserSetting> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(AppUserSetting::getOpenid, openid);
        queryWrapper.eq(AppUserSetting::getIsPrimary, "1");

        AppUserSetting appUserSetting = this.getOne(queryWrapper);

        if (appUserSetting != null) {
            return appUserSetting;
        }

        return null;
    }

    /**
     * 取消主账号
     *
     * @author zwf
     * @date created in 2025-06-18 09:33
     * @param: userId
     * @return: java.lang.Boolean
     */
    @Override
    public Boolean setNotPrimary(String userId) {
        LambdaQueryWrapper<AppUserSetting> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(AppUserSetting::getUserId, userId);
        queryWrapper.eq(AppUserSetting::getIsPrimary, "1");

        List<AppUserSetting> list = this.list(queryWrapper);

        if (list.size() > 0) {
            list.forEach(item -> item.setIsPrimary("0"));

            return this.updateBatchById(list);
        } else {
            return true;
        }
    }

    /**
     * 更新所有账号与主账号同步
     *
     * @author zwf
     * @date created in 2025-06-18 09:43
     * @param: userId
     * @return: java.lang.Boolean
     */
    @Override
    public Boolean updateUserPrimary(String userId, AppUserSetting userSetting) {
        // 查询所有非主账号
        LambdaQueryWrapper<AppUserSetting> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(AppUserSetting::getUserId, userId);
        queryWrapper.eq(AppUserSetting::getIsPrimary, "0");

        List<AppUserSetting> list = this.list(queryWrapper);

        if (!list.isEmpty()) {
            list.forEach(item -> {
                item.setRemindType(userSetting.getRemindType());
                item.setPlateNumber(userSetting.getPlateNumber());
                item.setRemindCount(userSetting.getRemindCount());
                item.setAccountCount(userSetting.getAccountCount());
                item.setMemoCount(userSetting.getMemoCount());
                item.setUpdateBy(userId);
                item.setUpdateTime(new Date());
            });

            return this.updateBatchById(list);
        } else {
            return true;
        }
    }

    /**
     * 修改用户信息
     *
     * @author zwf
     * @date created in 2025-06-26 09:14
     * @param: params
     * @return: org.jeecg.common.api.vo.Result<java.lang.String>
     */
    @Override
    public Result<String> updateUserInfo(JSONObject params) {
        Result<String> result = new Result<>();
        result = Result.error("修改失败");
        if (params != null && !params.isEmpty()) {
            if (params.containsKey("value") && params.containsKey("field")) {
                String value = params.getString("value");
                String field = params.getString("field");

                if (value != null && field != null && !value.isEmpty() && !field.isEmpty()) {
                    LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                    SysUser user = userService.getById(loginUser.getId());
                    if ("phone".equals(field)) {
                        // 校验
                        SysUser userByPhone = userService.getUserByPhone(value);
                        if (userByPhone != null) {
                            return Result.error("手机号已被绑定");
                        }
                    }
                    if ("email".equals(value)) {
                        // 校验
                        SysUser userByEmail = userService.getUserByEmail(value);
                        if (userByEmail != null) {
                            return Result.error("邮箱已被绑定");
                        }
                    }
                    switch (field) {
                        case "realname":
                            user.setRealname(value);
                            break;
                        case "sex":
                            user.setSex(Integer.parseInt(value));
                            break;
                        case "birthday":
                            Date date = getDate(value);
                            if (date != null) {
                                user.setBirthday(date);
                            } else {
                                return Result.error("生日格式错误");
                            }
                            break;
                        case "phone":
                            user.setPhone(value);
                            break;
                        case "email":
                            user.setEmail(value);
                            break;
                        case "password":
                            user.setPassword(value);
                            userService.changePassword(user);
                            break;
                        case "vip":
                        case "gift":
                            // 兑换/升级vip
                            analysisCode(user, value);
                            break;
                        case "cancel":
                            // 注销账号
                            user.setDelFlag(1);
                            user.setStatus(1);
                            break;
                        case "remindType":
                            AppUserSetting userSetting = this.getByUserId(loginUser.getId());

                            userSetting.setRemindType(value);

                            boolean update = this.updateById(userSetting);

                            if (update) {
                                return Result.ok("修改成功");
                            } else {
                                return Result.ok("修改失败");
                            }
                    }
                    boolean update = userService.updateById(user);

                    if (update) {
                        result = Result.ok("修改成功");
                    }
                }
            }
        }
        return result;
    }

    /**
     * 修改头像
     *
     * @author zwf
     * @date created in 2025-06-26 15:11
     * @param: file
     * @return: org.jeecg.common.api.vo.Result<java.lang.String>
     */
    @Override
    public Result<String> uploadAvatar(MultipartFile file) {
        try {
            // 1. 文件验证
            if (file.isEmpty()) {
                return Result.error("文件为空");
            }

            // 2. 文件大小限制（例如：5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.error("文件大小不能超过5MB");
            }

            // 3. 文件类型验证
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只能上传图片文件");
            }

            // 4. 获取当前用户
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (loginUser == null) {
                return Result.error("用户未登录");
            }

            // 5. 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = "Avatar-" + loginUser.getId() + "-" + System.currentTimeMillis() + "." + extension;

            String fileUrl = MinioUtil.upload(file, "avatar/" + fileName);

            if (fileUrl != null && !fileUrl.isEmpty()) {
                SysFiles fileAvatar = new SysFiles();

                fileAvatar.setFileName(fileName);
                fileAvatar.setUrl(fileUrl);
                fileAvatar.setFileType(extension);
                fileAvatar.setStoreType("avatar");
                fileAvatar.setFileSize(file.getSize() / 1024.0);
                fileAvatar.setDelFlag("0");
                fileAvatar.setCreateTime(new Date());
                fileAvatar.setCreateBy(loginUser.getId());

                filesService.save(fileAvatar);

                // 6. 更新用户头像信息
                SysUser user = userService.getById(loginUser.getId());
                user.setAvatar(fileUrl);
                userService.updateById(user);

                return Result.ok(fileUrl);
            } else {
                return Result.error("头像上传失败");
            }


        } catch (Exception e) {
            log.error("头像上传失败", e);
            return Result.error("头像上传失败");
        }
    }

    private Date getDate(String value) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date birthday = sdf.parse(value);
            return birthday;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 兑换/升级vip
     *
     * @author zwf
     * @date created in 2025-06-26 10:17
     * @param: user
     * @param: value
     */
    private void analysisCode(SysUser user, String value) {
    }


    /**
     * 获取微信session openid unionid
     *
     * @author zwf
     * @date created in 2025-06-13 08:31
     * @param: code
     * @return: com.alibaba.fastjson.JSONObject
     */
    public JSONObject getWeChatSession(String code) {
        // 构建请求URL
        String url = String.format("%s/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                sso,
                appId,
                appSecret,
                code);
        JSONObject result = new JSONObject();
        try {
            String response = HttpUtil.get(url);
            // 将响应转换为JSONObject
            result = JSONObject.parseObject(response);
            // 检查微信接口返回的错误码
            if (result.containsKey("errcode")) {
                log.error("微信接口错误: " + result.getString("errmsg"));
            }
        } catch (Exception e) {
            log.error("获取微信session失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 根据用户id获取扩展设置
     *
     * @author zwf
     * @date created in 2025-06-13 09:32
     * @param: userId
     * @return: org.jeecg.modules.appUser.entity.AppUserSetting
     */
    @Override
    public AppUserSetting getByUserId(String userId) {

        LambdaQueryWrapper<AppUserSetting> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(AppUserSetting::getUserId, userId);
        queryWrapper.eq(AppUserSetting::getIsPrimary, "1");

        AppUserSetting appUserSetting = this.getOne(queryWrapper);

        if (appUserSetting != null) {
            return appUserSetting;
        }

        return null;
    }
}
